package com.ferret.service;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ferret.bean.Constants;
import com.ferret.bean.dto.DeviceIdObject;
import com.ferret.bean.dto.ResponseStatusObject;
import com.ferret.bean.entity.VIIDServer;
import com.ferret.bean.vo.RegisterRequest;
import com.ferret.security.DigestData;
import com.ferret.utils.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@Service
public class VIIDServerService {
    private final Logger logger = LoggerFactory.getLogger(getClass());


    public VIIDServer getByIdAndEnabled(String id) {
        VIIDServer viidServer = null;
//                viidServerDao.findByServerIdAndEnabled(id, 1);
        return viidServer;
    }


    public VIIDServer getCurrentServer() {
        return getCurrentServer(true);
    }

    public VIIDServer getCurrentServer(boolean useCache) {
        VIIDServer viidServer =  null;
//                viidServerDao.findByCategory(Constants.VIID_SERVER.SERVER_CATEGORY.GATEWAY);
        return viidServer;
    }

    public VIIDServer register(RegisterRequest request, HttpServletRequest servletRequest, DigestData digestData) throws Exception {
        String serverId = Optional.ofNullable(request)
                .map(RegisterRequest::getRegisterObject)
                .map(DeviceIdObject::getDeviceId)
                .orElse(null);
        VIIDServer viidServer = this.getByIdAndEnabled(serverId);
        if (!ObjectUtil.isNotEmpty(viidServer)) {
            viidServer = new VIIDServer();
            viidServer.setHost(IpUtils.getIpAddr(servletRequest));
            viidServer.setServerId(serverId);
        }
        digestData.setUsername(viidServer.getUsername());
        digestData.validateAndDecode(DigestData.DIGEST_KEY, DigestData.DIGEST_REALM);
        return viidServer;
    }

    public ResponseStatusObject keepalive(String deviceId) {
        VIIDServer viidServer = null;
//                viidServerDao.getOne(deviceId);
        ResponseStatusObject statusObject;
        if (ObjUtil.isNotEmpty(viidServer)) {
            logger.info(deviceId + "：：保活成功");
            statusObject = new ResponseStatusObject("/VIID/System/Keepalive", "0", "ok");
        } else {
            logger.error(deviceId + "：：保活失败");
            statusObject = new ResponseStatusObject("/VIID/System/Keepalive", "500", "保活失败,请先注册");
        }
        return statusObject;
    }
}
